/**
 * Copyright (c) 2015 https://github.com/howiefh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.tyijian.admin.service;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.tyijian.admin.entity.SysRole;
import com.tyijian.admin.repository.jpa.RoleDao;
import com.tyijian.springside.core.persistence.DynamicSpecifications;
import com.tyijian.springside.core.persistence.SearchFilter;

/**
 *
 *
 * @author yangjp
 */
@Component
@Transactional
public class RoleService {
    @Autowired
    private RoleDao roleDao;

    /**
     * 查找role
     * 
     * @param id
     * @return
     */
    public SysRole get(Long id){
    	return roleDao.findOne(id);
    }
    
	/**
	 * 
	 * 得到分页role 对象
	 * 
	 * @param userId
	 * @param searchParams
	 * @param pageNumber
	 * @param pageSize
	 * @param sortType
	 * @return
	 */
	public Page<SysRole> getRolePageList(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType) {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
		Specification<SysRole> spec = buildSpecification(searchParams);
		return roleDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pageSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		} else if ("name".equals(sortType)) {
			sort = new Sort(Direction.ASC, "name");
		}
		return new PageRequest(pageNumber - 1, pageSize, sort);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<SysRole> buildSpecification(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		Specification<SysRole> spec = DynamicSpecifications.bySearchFilter(filters.values(), SysRole.class);
		return spec;
	}
    
    
    /**
     * 删除role
     * @param id
     */
    public void delete(SysRole role){
    	roleDao.delete(role);
    }
    
    /**
     * 保存 role 
     * @param role实体
     */
    public void save(SysRole role){
    	roleDao.save(role);
    }
    
}